package com.xbongbong.pro.aiassistant.service.impl;

import com.alibaba.fastjson.JSON;
import com.xbongbong.aiassistant.domain.entity.AiContactEntity;
import com.xbongbong.aiassistant.domain.entity.AiContractEntity;
import com.xbongbong.aiassistant.domain.entity.AiCustomerEntity;
import com.xbongbong.aiassistant.domain.entity.AiOpportunityEntity;
import com.xbongbong.aiassistant.domain.entity.AiPayPlanEntity;
import com.xbongbong.aiassistant.domain.entity.AiPaymentEntity;
import com.xbongbong.aiassistant.domain.entity.AiProductEntity;
import com.xbongbong.aiassistant.domain.entity.AiProductionOrderEntity;
import com.xbongbong.aiassistant.domain.entity.AiPurchaseEntity;
import com.xbongbong.aiassistant.domain.entity.AiSupplierEntity;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.constant.SizeConstant;
import com.xbongbong.paas.constant.TimeConstant;
import com.xbongbong.paas.domain.entity.ext.ConditionsEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.enums.ConditionEnum;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateUtil;
import com.xbongbong.pro.aiassistant.AiAssistantConditionHelp;
import com.xbongbong.pro.aiassistant.handle.SaasAiAssistantStrategyHandle;
import com.xbongbong.pro.aiassistant.service.SmartSettingsEsService;
import com.xbongbong.pro.domain.entity.AiAssistantEntity;
import com.xbongbong.pro.domain.entity.AiAssistantHistoryEntity;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartSettingsConditionEnum;
import com.xbongbong.pro.enums.smartsettings.enums.SmartSettingsFieldEnum;
import com.xbongbong.pro.smartsettings.pojo.dto.SmartStrategyRabbitMqDTO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.enums.BirthdayFilterEnum;
import com.xbongbong.saas.enums.WarningSearchEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.CustomerManagementEnum;
import com.xbongbong.saas.enums.business.PayPlanEnum;
import com.xbongbong.saas.enums.business.PaymentEnum;
import com.xbongbong.saas.enums.business.ProductionOrderEnum;
import com.xbongbong.saas.enums.business.PurchaseEnum;
import com.xbongbong.saas.enums.business.SalesOpportunityEnum;
import com.xbongbong.saas.enums.business.SupplierEnum;
import com.xbongbong.saas.model.ContactModel;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.CustomerModel;
import com.xbongbong.saas.model.IndexTypeModel;
import com.xbongbong.saas.model.OpportunityModel;
import com.xbongbong.saas.model.PaasFormDataModel;
import com.xbongbong.saas.model.PayPlanModel;
import com.xbongbong.saas.model.PaymentModel;
import com.xbongbong.saas.model.ProductModel;
import com.xbongbong.saas.model.ProductionOrderModel;
import com.xbongbong.saas.model.PurchaseModel;
import com.xbongbong.saas.model.SupplierModel;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.elasticsearch.index.query.QueryBuilders.termsQuery;

/**
 * @description: 智能助手-数据查询
 * @Author: hongxiao
 * @date: 2019-05-09 11:02
 * @since v1.0
 */
@Service("smartSettingsEsService")
public class SmartSettingsEsServiceImpl implements SmartSettingsEsService {

    private static Logger LOG = LoggerFactory.getLogger(SmartSettingsEsServiceImpl.class);

    @Resource
    private PaasFormDataModel paasFormDataModel;
    @Resource
    private EsHelper esHelper;
    @Resource
    private CustomerModel customerModel;
    @Resource
    private ContactModel contactModel;
    @Resource
    private OpportunityModel opportunityModel;
    @Resource
    private ContractModel contractModel;
    @Resource
    private ProductModel productModel;
    @Resource
    private SupplierModel supplierModel;
    @Resource
    private PurchaseModel purchaseModel;
    @Resource
    private PaymentModel paymentModel;
    @Resource
    private PayPlanModel payPlanModel;
    @Resource
    private ProductionOrderModel productionOrderModel;
    @Resource
    private SaasAiAssistantStrategyHandle saasAiAssistantStrategyHandle;
    @Resource
    private AiAssistantConditionHelp aiAssistantConditionHelp;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private IndexTypeModel indexTypeModel;


    @Override
    public void getDataIds(SmartStrategyRabbitMqDTO rabbitMqDTO, Map<Long, List<Long>> dataIdsMap) {
        // 查询条件准备
        List<AiAssistantEntity> list = rabbitMqDTO.getList();
        String corpid = rabbitMqDTO.getCorpid();


        List<ConditionsEntityExt> allConditionList = new ArrayList<>();
        for (AiAssistantEntity entity : list) {
            List<ConditionsEntityExt> conditionList = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
            allConditionList.addAll(conditionList);
        }

        // 获取是否有关联数据查询的触发条件
        Map<String, Boolean> linkDataFlagMap = aiAssistantConditionHelp.getLinkDataFlag(allConditionList);

        Set<Long> waitPurchaseDataIdSet = new HashSet<>();
        Set<Long> waitProduceDataIdSet = new HashSet<>();
        // 待生产
        if (linkDataFlagMap.containsKey(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getAlias())) {
            waitProduceDataIdSet = saasAiAssistantStrategyHandle.getWaitProduceDataIds(corpid);
        }
        // 待采购
        if (linkDataFlagMap.containsKey(SmartSettingsFieldEnum.WAIT_PURCHASE.getAlias())) {
            waitPurchaseDataIdSet = saasAiAssistantStrategyHandle.getWaitPurchaseDataIds(corpid);
        }

        // 通用筛选条件
        List<ConditionsEntityExt> conditionList = new ArrayList<>();
        // 产品下限预警、产品保质期预警
        List<ConditionsEntityExt> stockWarningConditionList = new ArrayList<>();
        List<ConditionsEntityExt> expireWarningConditionList = new ArrayList<>();
        // 生日筛选条件
        List<ConditionsEntityExt> birthdayConditionList = new ArrayList<>();

        for (AiAssistantEntity entity : list) {
            // 工作报告不处理
            if(Objects.equals(SaasMarkEnum.SAAS.getCode(), entity.getSaasMark()) && Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), entity.getBusinessType())) {
                continue;
            }
            conditionList.clear();
            stockWarningConditionList.clear();
            expireWarningConditionList.clear();
            birthdayConditionList.clear();
            LOG.info("corpid：" + corpid + "，执行策略搜索数据：" + entity.getName() + "；策略id：" + entity.getId());
            // 添加筛选条件
            aiAssistantConditionHelp.addConditionList(entity, conditionList, birthdayConditionList, stockWarningConditionList, expireWarningConditionList, waitProduceDataIdSet, waitPurchaseDataIdSet);
            if (conditionList.isEmpty() && stockWarningConditionList.isEmpty() && expireWarningConditionList.isEmpty() && birthdayConditionList.isEmpty()) {
                continue;
            }
            int saasMark = entity.getSaasMark();
            // es查询
            BoolQueryBuilder boolQueryBuilder = boolQuery();

            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            try {
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, entity.getBusinessType(), saasMark);

                // 筛选条件
                if (!conditionList.isEmpty()) {
                    EsUtil.parseCondition(boolQueryBuilder, conditionList, "", corpid, entity.getBusinessType());
                }
                // 生日特殊处理
                if (!birthdayConditionList.isEmpty()) {
                    Integer day = 0;
                    for(ConditionsEntityExt conditionsEntityExt : birthdayConditionList) {
                        try {
                            List<Object> valueList = conditionsEntityExt.getValue();
                            if(!valueList.isEmpty()) {
                                day = Integer.valueOf(valueList.get(0).toString());
                            }
                        } catch (NumberFormatException e) {
                            day = 0;
                        }
                        EsUtil.conditionBirthday(boolQueryBuilder, BirthdayFilterEnum.REMIND.getValue(), day);
                    }
                }
                // 产品下限/上限预警
                if (!stockWarningConditionList.isEmpty()) {
                    EsUtil.parseProductSearchCondition(boolQueryBuilder, stockWarningConditionList, "", corpid, XbbRefTypeEnum.WARNING_SEARCH.getCode());
                }
                // 产品保质期预警
                if (!expireWarningConditionList.isEmpty()) {
                    EsUtil.parseProductSearchCondition(boolQueryBuilder, expireWarningConditionList, "", corpid, XbbRefTypeEnum.GUARANTEE_SEARCH.getCode());
                }
            } catch (Exception e) {
                LOG.error("smartSettingsEsService error：", e);
                continue;
            }

            // 添加corpid,formId,del
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("formId", entity.getFormId()));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));
            //无需审批和通过
            boolQueryBuilder.filter(termsQuery("flowStatus", FlowStatusEnum.getStatisticType()));



            List<PaasFormDataEntityExt> dataList = new ArrayList<>();
            try {
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, entity.getBusinessType(), saasMark);

                XbbAggregatedPage<PaasFormDataEntityExt> aggregatedPage = esHelper.findByPage(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList, 1, SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE, new ArrayList<>());
                if (Objects.nonNull(aggregatedPage)) {
                    dataList = aggregatedPage.getContent();
                }
            } catch (Exception e) {
                LOG.error("aiEs:dataList", e);
                continue;
            }
            if (dataList.size() >= SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE) {
                LOG.info("corpid：" + corpid + "检索的数据量大于等于" + SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE + "，不在执行策略：" + entity.getName() + "；策略id：" + entity.getId());
                continue;
            }

            List<Long> dataIds = new ArrayList<>();
            if (dataList.size() > 0) {
                dataList.forEach(item -> {
                    dataIds.add(item.getDataId());
                });
                dataIdsMap.put(entity.getId(), dataIds);
            }
        }

    }


    @Override
    public void getFormDataList(SmartStrategyRabbitMqDTO rabbitMqDTO, Map<Long, List<Long>> dataIdsMap,
                                Map<Integer, List<PaasFormDataEntityExt>> saasDataList, List<PaasFormDataEntityExt> paasDataList) throws XbbException {
        Map<Integer, Set<Long>> saasDataIdsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        Set<Long> paasDataIds = new HashSet<>();

        List<AiAssistantEntity> aiAssistantEntityList = rabbitMqDTO.getList();
        for (AiAssistantEntity entity : aiAssistantEntityList) {
            if(Objects.equals(SaasMarkEnum.SAAS.getCode(), entity.getSaasMark()) && Objects.equals(XbbRefTypeEnum.WORK_REPORT.getCode(), entity.getBusinessType())) {
                continue;
            }
            if (!dataIdsMap.containsKey(entity.getId())) {
                continue;
            }
            List<Long> dataIds = dataIdsMap.get(entity.getId());
            if (Objects.equals(SaasMarkEnum.SAAS.getCode(), entity.getSaasMark())) {
                Integer businessType = entity.getBusinessType();
                if (saasDataIdsMap.containsKey(businessType)) {
                    saasDataIdsMap.get(businessType).addAll(dataIds);
                } else {
                    saasDataIdsMap.put(businessType, new HashSet<>(dataIds));
                }
            } else if (Objects.equals(SaasMarkEnum.PAAS.getCode(), entity.getSaasMark())) {
                paasDataIds.addAll(dataIds);
            }
        }

        if (!saasDataIdsMap.isEmpty()) {
            for (Map.Entry<Integer, Set<Long>> entry : saasDataIdsMap.entrySet()) {
                List<Long> allDataIdList = new ArrayList<>(entry.getValue());
                List<PaasFormDataEntityExt> dataList = getSaasDataList(rabbitMqDTO.getCorpid(), entry.getKey(), allDataIdList);
                saasDataList.put(entry.getKey(), dataList);
            }
        }


        if (!paasDataIds.isEmpty()) {
            // 只查询需要的数据，paas表单暂时不查data数据，减少数据量
            String columns = "id, corpid, app_id, menu_id, form_id, serial_no,owner_id,department_id, creator_id";
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("corpid", rabbitMqDTO.getCorpid());
            param.put("columns", columns);

            // 分页查询
            List<Long> allDataIdList = new ArrayList<>(paasDataIds);
            int count = paasDataIds.size();
            int start = 0;
            int pageNum = 2000;
            for (; start <= count; start = start + pageNum) {
                // 分组数据的endIndex
                int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                List<Long> dataIds = allDataIdList.subList(start, endIndex);
                param.put("ids", dataIds);
                List<PaasFormDataEntityExt> list = paasFormDataModel.findEntitys(param);
                paasDataList.addAll(list);
            }
        }
    }


    @Override
    public Map<Long, List<Long>> getValidDataIds(SmartStrategyRabbitMqDTO rabbitMqDTO, Map<Long, List<Long>> waitInvalidIdsMap,
                                                 Map<Long, List<AiAssistantHistoryEntity>> waitInvalidListMap) {

        Map<Long, List<Long>> validIdsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        // 无待失效数据
        if(waitInvalidIdsMap.isEmpty()) {
            return validIdsMap;
        }

        // ================ 查询这些数据是否有效 ================
        List<AiAssistantEntity> list = rabbitMqDTO.getList();
        String corpid = rabbitMqDTO.getCorpid();

        // 正常查询的智能助手
        List<AiAssistantEntity> normalSmartList = new ArrayList<>();
        List<ConditionsEntityExt> triggerConditions = new ArrayList<>();
        for (AiAssistantEntity entity : list) {
            if(waitInvalidIdsMap.containsKey(entity.getId())) {
                Long smartId = entity.getId();
                List<ConditionsEntityExt> conditionList = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
                triggerConditions.addAll(conditionList);
                // 多触发条件
                if(conditionList.size() > 1) {
                    triggerConditions.addAll(conditionList);

                    normalSmartList.add(entity);
                } else if(conditionList.size() == 1) {
                    // 自然失效
                    if(naturalInvalid(conditionList.get(0))) {
                        validIdsMap.put(smartId, waitInvalidIdsMap.get(entity.getId()));
                    } else {
                        triggerConditions.addAll(conditionList);
                        normalSmartList.add(entity);
                    }
                }
            }
        }

        // 获取是否有关联数据查询的触发条件
        Map<String, Boolean> linkDataFlagMap = aiAssistantConditionHelp.getLinkDataFlag(triggerConditions);

        Set<Long> waitPurchaseDataIdSet = new HashSet<>();
        Set<Long> waitProduceDataIdSet = new HashSet<>();
        // 待生产
        if (linkDataFlagMap.containsKey(SmartSettingsFieldEnum.WAIT_PRODUCTION_ORDER.getAlias())) {
            waitProduceDataIdSet = saasAiAssistantStrategyHandle.getWaitProduceDataIds(corpid);
        }
        // 待采购
        if (linkDataFlagMap.containsKey(SmartSettingsFieldEnum.WAIT_PURCHASE.getAlias())) {
            waitPurchaseDataIdSet = saasAiAssistantStrategyHandle.getWaitPurchaseDataIds(corpid);
        }


        for (AiAssistantEntity entity : normalSmartList) {

            // 通用筛选条件
            List<ConditionsEntityExt> conditionList = new ArrayList<>();
            // 产品下限预警、产品保质期预警
            List<ConditionsEntityExt> stockWarningConditionList = new ArrayList<>();
            List<ConditionsEntityExt> expireWarningConditionList = new ArrayList<>();

            // 上次执行时间对应的数据记录{timestamp: [dataId1, dataId2]}
//            Map<Long, List<Long>> timeDataIdsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            List<AiAssistantHistoryEntity> waitInvalidList = waitInvalidListMap.get(entity.getId());
            Long thenTime = DateUtil.getZero4SomeDay(waitInvalidList.get(0).getUpdateTime());

            // 添加筛选条件
            validConditionList(entity, thenTime, conditionList, stockWarningConditionList, expireWarningConditionList, waitProduceDataIdSet, waitPurchaseDataIdSet);
            // TODO 添加数据ids,不同时间对应的数据ids没有想好怎么处理
            List<Long> queryDataIds = waitInvalidIdsMap.get(entity.getId());
            ConditionsEntityExt dataIdsEntityExt = new ConditionsEntityExt(FieldTypeEnum.DATAID.getAlias(), "", FieldTypeEnum.DATAID.getType(), ConditionEnum.IN.getSymbol(), new ArrayList<>(queryDataIds));
            conditionList.add(dataIdsEntityExt);

            if (conditionList.isEmpty() && stockWarningConditionList.isEmpty() && expireWarningConditionList.isEmpty()) {
                continue;
            }
            int saasMark = entity.getSaasMark();
            // es查询
            BoolQueryBuilder boolQueryBuilder = boolQuery();
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery(StringConstant.DEL, DelEnum.NORMAL.getDel()));

            List<String> fieldList = new ArrayList<>();
            fieldList.add(StringConstant.DATA_ID);
            try {

                // 筛选条件
                if (!conditionList.isEmpty()) {
                    EsUtil.parseCondition(boolQueryBuilder, conditionList, "", corpid, entity.getBusinessType());
                }
                // 产品下限/上限预警
                if (!stockWarningConditionList.isEmpty()) {
                    EsUtil.parseProductSearchCondition(boolQueryBuilder, stockWarningConditionList, "", corpid, XbbRefTypeEnum.WARNING_SEARCH.getCode());
                }
                // 产品保质期预警
                if (!expireWarningConditionList.isEmpty()) {
                    EsUtil.parseProductSearchCondition(boolQueryBuilder, expireWarningConditionList, "", corpid, XbbRefTypeEnum.GUARANTEE_SEARCH.getCode());
                }
            } catch (XbbException e) {
                continue;
            }

            // 添加corpid,formId,del
            boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
            boolQueryBuilder.filter(termQuery("formId", entity.getFormId()));
            boolQueryBuilder.filter(termQuery("del", DelEnum.NORMAL.getDel()));
            //无需审批和通过
            boolQueryBuilder.filter(termsQuery("flowStatus", FlowStatusEnum.getStatisticType()));



            List<PaasFormDataEntityExt> dataList = new ArrayList<>();
            try {
                if (Objects.equals("ding51d0a413630fcca735c2f4657eb6378f", corpid)) {
                    XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(entity.getBusinessType());
                    LOG.error("SmartSettingsEsServiceImpl:getValidDataIds"  + refTypeEnum.getAlias() +  ":" + JSON.toJSONString(boolQueryBuilder));
                }
                IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(corpid, entity.getBusinessType(), saasMark);

                XbbAggregatedPage<PaasFormDataEntityExt> aggregatedPage = esHelper.findByPage(indexTypeEnum, boolQueryBuilder, PaasFormDataEntityExt.class, fieldList, 1, SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE, new ArrayList<>());
                if (Objects.nonNull(aggregatedPage)) {
                    dataList = aggregatedPage.getContent();
                }
                if (Objects.equals("ding51d0a413630fcca735c2f4657eb6378f", corpid)) {
                    XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(entity.getBusinessType());
                    LOG.error("SmartSettingsEsServiceImpl:getValidDataIds"  + refTypeEnum.getAlias() + JSON.toJSONString(dataList));
                }
            } catch (XbbException e) {
                LOG.info("aiEs:getValidDataIds:dataList", e);
                continue;
            }
            if (dataList.size() >= SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE) {
                LOG.info("corpid：" + corpid + "检索的数据量大于等于" + SizeConstant.AI_ASSISTANT_MAX_PAGE_SIZE + "，不在执行策略：" + entity.getName() + "；策略id：" + entity.getId());
                continue;
            }
            List<Long> dataIds = new ArrayList<>();
            if (dataList.size() > 0) {
                dataList.forEach(item -> {
                    dataIds.add(item.getDataId());
                });
                validIdsMap.put(entity.getId(), dataIds);
            }
        }

        return validIdsMap;
    }





    /**
     *
     * @param thenTime 上次执行日期时间戳
     * @param now 当天时间戳
     * @param value 筛选值列表
     * @param symbol 筛选条件
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-25 16:47
     * @since v1.0
     * @version v1.0
     */
    private Map<String, Object> getValidForgetDateRange(long thenTime, long now, List<Object> value, String symbol) {

        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
        if (conditionEnum == null) {
            return null;
        }

        long startDay = 0;
        long endDay = 0;
        if (value.size() == BasicConstant.TWO) {
            startDay = Long.parseLong(value.get(0).toString());
            endDay = Long.parseLong(value.get(1).toString());
        } else if (value.size() == BasicConstant.ONE) {
            startDay = Long.parseLong(value.get(0).toString());
        }
        symbol = ConditionEnum.RANGE.getSymbol();

        List<Long> timeRange = new ArrayList<>(2);
        switch (conditionEnum) {
            // 遗忘提醒都是区间（不包含未跟进客户/机会/供应商）
            case GREATERTHAN:
                timeRange.add(1L);
                timeRange.add(now - startDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                break;
            case GREATEREQUAL:
                // 初值必须大于0
                timeRange.add(1L);
                timeRange.add(now - (startDay - 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                break;
            case LESSTHAN:
                timeRange.add(now - (startDay - 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                timeRange.add(now);
                break;
            case LESSEQUAL:
                timeRange.add(now - startDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                timeRange.add(now);
                break;
            case RANGE:
                timeRange.add(now - endDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                timeRange.add(now - startDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                break;
            default:
                break;
        }
        Map<String, Object> resultMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        resultMap.put("symbol", symbol);
        resultMap.put("value", timeRange);
        return resultMap;
    }




    /**
     * 获取回款/付款的到期/逾期筛选条件
     *
     * @param attr 别名
     * @param fieldType 类型
     * @param symbol 操作符
     * @param value 值列表
     * @param thenTime 上次执行的日期（时间戳）
     * @param now 当前日期（时间戳）
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-25 17:17
     * @since v1.0
     * @version v1.0
     */
    private ConditionsEntityExt getValidEstimateTimeRange(String attr, Integer fieldType, String symbol, List<Object> value, long thenTime, long now) {
        SmartSettingsConditionEnum conditionEnum = SmartSettingsConditionEnum.getBySymbol(symbol);
        symbol = ConditionEnum.RANGE.getSymbol();

        if (conditionEnum == null) {
            value.clear();
            value.add(now);
            value.add(now + TimeConstant.SECONDS_PER_DAY);
        } else {
            long day = 0;
            if (value.size() > 0) {
                day = Long.parseLong(value.get(0).toString());
            }
            value.clear();
            switch (conditionEnum) {
                // 之前(到期）
                case BEFORE:
                    value.add(now + day * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    value.add(now + (day + 1) * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    break;
                // 之后（逾期）
                case AFTER:
                    value.add(now - day * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    value.add(now - (day - 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    break;
                // 当天
                default:
                    value.add(now);
                    value.add(now + TimeConstant.SECONDS_PER_DAY);
                    break;
            }
        }

        ConditionsEntityExt entityExt = new ConditionsEntityExt();
        // attr、fieldType、symbol、value改为查询的类型
        entityExt.setAttr(attr);
        entityExt.setFieldType(fieldType);
        entityExt.setSymbol(symbol);
        entityExt.setValue(value);
        return entityExt;
    }


    /**
     * 保质期筛选条件
     *
     * @param attr 别名
     * @param fieldType 类型
     * @param value 值列表
     * @param now 当前日期（时间戳）
     * @throws
     * @return
     * @author hongxiao
     * @date 2019-12-17 15:19
     * @since
     * @version
     */
    private ConditionsEntityExt getValidExpireTimeRange(String attr, Integer fieldType, String symbol, List<Object> value, long thenTime, long now) {

        // 保质期：大于、大于等于、小于、小于等于、选择范围
        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
        List<Object> timeRange = new ArrayList<>(BasicConstant.TWO);
        if (conditionEnum == null) {
            timeRange.add(now);
            timeRange.add(now + TimeConstant.SECONDS_PER_DAY);
            symbol = ConditionEnum.RANGE.getSymbol();
        } else {
            long startDay = 0;
            long endDay = 0;
            if (value.size() == BasicConstant.TWO) {
                startDay = Long.parseLong(value.get(0).toString());
                endDay = Long.parseLong(value.get(1).toString());
            } else if (value.size() == BasicConstant.ONE) {
                startDay = Long.parseLong(value.get(0).toString());
            }

            switch (conditionEnum) {
                // 大于
                case GREATERTHAN:
                    timeRange.add(now + (startDay + 1) * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    break;
                // 大于等于/小于等于
                case GREATEREQUAL:
                case LESSEQUAL:
                    timeRange.add(now + startDay * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    break;
                // 小于
                case LESSTHAN:
                    timeRange.add(now + (startDay - 1) * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    break;
                case RANGE:
                    timeRange.add(now + startDay * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    timeRange.add(now + (endDay + 1) * TimeConstant.SECONDS_PER_DAY - (now - thenTime));
                    symbol = ConditionEnum.RANGE.getSymbol();
                    break;
                default:
                    break;
            }
        }


        ConditionsEntityExt entityExt = new ConditionsEntityExt();
        // attr、fieldType、symbol、value改为查询的类型
        entityExt.setAttr(attr);
        entityExt.setFieldType(fieldType);
        entityExt.setSymbol(symbol);
        entityExt.setValue(timeRange);
        return entityExt;
    }



    /**
     * 获取未处理筛选条件（待采购/待生产/待出库/待入库）
     *
     * @param thenTime 上次执行的日期（时间戳）
     * @param now 当前日期（时间戳）
     * @param value 筛选值
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-25 17:24
     * @since v1.0
     * @version v1.0
     */
    private ConditionsEntityExt getValidUntreatedDateRange(String symbol, long thenTime, long now, List<Object> value) {


        // 待：大于、大于等于、小于、小于等于、选择范围
        ConditionEnum conditionEnum = ConditionEnum.getConditionEnum(symbol);
        List<Object> timeRange = new ArrayList<>(BasicConstant.TWO);
        if (conditionEnum == null) {
            timeRange.add(now);
            timeRange.add(now + TimeConstant.SECONDS_PER_DAY);
            symbol = ConditionEnum.RANGE.getSymbol();
        } else {
            long startDay = 0;
            long endDay = 0;
            if (value.size() == BasicConstant.TWO) {
                startDay = Long.parseLong(value.get(0).toString());
                endDay = Long.parseLong(value.get(1).toString());
            } else if (value.size() == BasicConstant.ONE) {
                startDay = Long.parseLong(value.get(0).toString());
            }

            switch (conditionEnum) {
                // 大于
                case GREATERTHAN:
                    timeRange.add(now - startDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    symbol = ConditionEnum.LESSTHAN.getSymbol();
                    break;
                // 大于等于/小于等于
                case GREATEREQUAL:
                    timeRange.add(now - (startDay - 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    symbol = ConditionEnum.GREATEREQUAL.getSymbol();
                    break;
                // 小于
                case LESSTHAN:
                    timeRange.add(now - (startDay + 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    timeRange.add(now);
                    symbol = ConditionEnum.RANGE.getSymbol();
                    break;
                case LESSEQUAL:
                    timeRange.add(now - startDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    timeRange.add(now);
                    symbol = ConditionEnum.RANGE.getSymbol();
                    break;
                case RANGE:
                    timeRange.add(now - endDay * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    timeRange.add(now - (startDay - 1) * TimeConstant.SECONDS_PER_DAY + (now - thenTime));
                    symbol = ConditionEnum.RANGE.getSymbol();
                    break;
                default:
                    break;
            }
        }

        ConditionsEntityExt entityExt = new ConditionsEntityExt();
        // attr、fieldType、symbol、value改为查询的类型
        entityExt.setAttr(FieldTypeEnum.ADDTIME.getAlias());
        entityExt.setFieldType(FieldTypeEnum.ADDTIME.getType());
        entityExt.setSymbol(symbol);
        entityExt.setValue(timeRange);
        return entityExt;
    }

    @Override
    public List<PaasFormDataEntityExt> getPaasDataList(String corpid, Integer saasMark, List<Long> paasDataIds) {
        if (Objects.equals(SaasMarkEnum.SAAS.getCode(), saasMark) || CollectionsUtil.isEmpty(paasDataIds)) {
            return new ArrayList<>();
        }
        // 只查询需要的数据，paas表单暂时不查data数据，减少数据量
        String columns = "id, corpid, app_id, menu_id, form_id, serial_no,owner_id,department_id, creator_id";
        Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        param.put(StringConstant.DEL, DelEnum.NORMAL.getDel());
        param.put(StringConstant.CORPID, corpid );
        param.put(StringConstant.COLUMNS, columns);

        // 分页查询
        param.put(StringConstant.IDIN, paasDataIds);
        List<PaasFormDataEntityExt> paasDataList = paasFormDataModel.findEntitysWithoutSub(param);
        return paasDataList;
    }


    /**
     * 获取saas数据
     *
     * @param corpid        公司id
     * @param businessType  业务类型
     * @param allDataIdList 数据ids
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-07-25 17:23
     * @version v1.0
     * @since v1.0
     */
    @Override
    public List<PaasFormDataEntityExt> getSaasDataList(String corpid, Integer businessType, List<Long> allDataIdList) {
        List<PaasFormDataEntityExt> dataList = new ArrayList<>();
        try {
            // 分页查询
            Map<String, Object> param = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
            param.put("del", DelEnum.NORMAL.getDel());
            param.put("corpid", corpid);

            int count = allDataIdList.size();
            int start = 0;
            int pageNum = 2000;

            XbbRefTypeEnum refTypeEnum = XbbRefTypeEnum.getByCode(businessType);
            switch (refTypeEnum) {
                case CUSTOMER_MANAGEMENT:
                    // data需要字段：名称、创建人、客户电话
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiCustomerEntity> list = customerModel.getCustomerList4Ai(corpid, dataIds);
                        for (AiCustomerEntity entity : list) {
                            entity.setData(entity.getName(), entity.getCreator(), entity.getPhone());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case CONTACT:
                    // data需要字段：名称、电话
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiContactEntity> list = contactModel.getContactList4Ai(corpid, dataIds);
                        for (AiContactEntity entity : list) {
                            entity.setData(entity.getName(), entity.getPhone());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case SALES_OPPORTUNITY:
                    // data需要字段：名称
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiOpportunityEntity> list = opportunityModel.getOpportunityList4Ai(corpid, dataIds);
                        for (AiOpportunityEntity entity : list) {
                            entity.setData(entity.getName());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case CONTRACT:
                    // data需要字段：名称、签订人
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiContractEntity> list = contractModel.getContractList4Ai(corpid, dataIds);
                        for (AiContractEntity entity : list) {
                            entity.setData(entity.getName(), entity.getSignPerson());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case PRODUCT:
                    // data需要字段：名称、产品编号、父产品id
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiProductEntity> list = productModel.getProductList4Ai(corpid, dataIds);
                        for (AiProductEntity entity : list) {
                            entity.setData(entity.getName(), entity.getProductNo(), entity.getParentId());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case SUPPLIER:
                    // data需要字段：名称
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiSupplierEntity> list = supplierModel.getSupplierList4Ai(corpid, dataIds);
                        for (AiSupplierEntity entity : list) {
                            entity.setData(entity.getName());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case PURCHASE:
                    // data需要字段：名称、签订人
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiPurchaseEntity> list = purchaseModel.getPurchaseList4Ai(corpid, dataIds);
                        for (AiPurchaseEntity entity : list) {
                            entity.setData(entity.getName(), entity.getSignerId());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case PAYMENT:
                    // data需要字段：关联合同
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiPaymentEntity> list = paymentModel.getPaymentList4Ai(corpid, dataIds);
                        for (AiPaymentEntity entity : list) {
                            entity.setData(entity.getContract());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case PAY_PLAN:
                    // data需要字段：关联采购合同
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiPayPlanEntity> list = payPlanModel.getPayPlanList4Ai(corpid, dataIds);
                        for (AiPayPlanEntity entity : list) {
                            entity.setData(entity.getLinkPurchase());
                        }
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                case PRODUCTION_ORDER:
                    // data需要字段: 无
                    for (; start <= count; start = start + pageNum) {
                        // 分组数据的endIndex
                        int endIndex = (start + pageNum) <= count ? start + pageNum : count;
                        List<Long> dataIds = allDataIdList.subList(start, endIndex);
                        List<AiProductionOrderEntity> list = productionOrderModel.getProductionOrderList4Ai(corpid, dataIds);
                        List<PaasFormDataEntityExt> formDataList = getFormDataList(list);
                        dataList.addAll(formDataList);
                    }
                    break;
                default:
                    dataList = formDataHelp.getByDataIdList(new HashSet<>(allDataIdList), businessType, SaasMarkEnum.SAAS.getCode(), null, corpid);
                    break;
            }
        } catch (Exception e) {
            LOG.error("获取数据失败", e);
        }

        return dataList;
    }




    /**
     * 自然失效的触发条件（根据执行次数计算）
     * @param entityExt 触发条件
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-24 20:32
     * @since v1.0
     * @version v1.0
     */
    private boolean naturalInvalid(ConditionsEntityExt entityExt) {
        Integer fieldType = entityExt.getFieldType();
        FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);

        boolean invalidFlag = false;

        if(fieldTypeEnum != null) {
            switch (fieldTypeEnum) {
                // 添加时间、更新时间、生日、日期类型
                case ADDTIME:
                case UPDATETIME:
                case BIRTHDAY:
                case DATETIME:
                    invalidFlag = true;
                    break;
                default:
                    break;
            }
        }

        return invalidFlag;

    }

    /**
     * 获取es查询条件
     *
     * @param
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-25 17:26
     * @since v1.0
     * @version v1.0
     */
    private void validConditionList(AiAssistantEntity entity, Long thenTime, List<ConditionsEntityExt> conditionList,
                                    List<ConditionsEntityExt> stockWarningConditionList, List<ConditionsEntityExt> expireWarningConditionList,
                                    Set<Long> waitProduceDataIdSet, Set<Long> waitPurchaseDataIdSet) {
        // TODO 当前时间为记录数据里的时间
        long now = DateUtil.getTodayInt();
//        long thenTime = DateUtil.getTodayInt();
//        // TODO 先取一个
//        for(Map.Entry<Long, List<Long>> entry : timeDataIdsMap.entrySet()) {
//            thenTime = entry.getKey();
//        }

        List<ConditionsEntityExt> conditions = entity.getTriggerCondition().toJavaList(ConditionsEntityExt.class);
        for (ConditionsEntityExt conditionsEntity : conditions) {
            // 是否为自然失效条件
            if(naturalInvalid(conditionsEntity)) {
                continue;
            }
            String attr = conditionsEntity.getAttr();
            Integer fieldType = conditionsEntity.getFieldType();
            String symbol = conditionsEntity.getSymbol();
            List<Object> value = conditionsEntity.getValue();
            FieldTypeEnum fieldTypeEnum = FieldTypeEnum.getFieldTypeEnum(fieldType);
            SmartSettingsFieldEnum ssFieldEnum = SmartSettingsFieldEnum.getFieldTypeEnum(fieldType);
            // attr、fieldType、symbol、value改为查询的类型
            if (fieldTypeEnum != null) {
                conditionList.add(aiAssistantConditionHelp.getConditionByFieldEnum(attr, fieldTypeEnum, symbol, value, thenTime));
            } else if (ssFieldEnum != null) {
                conditionList.addAll(getValidConditionBySsFieldEnum(ssFieldEnum, symbol, value, thenTime, now, waitProduceDataIdSet, waitPurchaseDataIdSet, stockWarningConditionList, expireWarningConditionList));
            }
        }
    }

    /**
     * 智能助手类型的es查询条件
     *
     * @param
     * @return
     * @throws
     * @author hongxiao
     * @date 2019-08-25 17:19
     * @since v1.0
     * @version v1.0
     */
    private List<ConditionsEntityExt> getValidConditionBySsFieldEnum(SmartSettingsFieldEnum ssFieldEnum, String symbol,
                             List<Object> value,long thenTime, long now, Set<Long> waitProduceDataIdSet, Set<Long> waitPurchaseDataIdSet,
                             List<ConditionsEntityExt> stockWarningConditionList, List<ConditionsEntityExt> expireWarningConditionList) {
        // 默认文本类型
        List<ConditionsEntityExt> list = new ArrayList<>();
        ConditionsEntityExt entityExt = new ConditionsEntityExt();
        switch (ssFieldEnum) {
            // 遗忘客户
            case FORGET_CUSTOMER:
                Map<String, Object> cusTimeRangeMap = getValidForgetDateRange(thenTime,now, value, symbol);
                List<Long> cusTimeRange = (List<Long>) cusTimeRangeMap.get("value");
                value.clear();
                value.addAll(cusTimeRange);
                // 客户-最近联系时间
                entityExt.setAttr(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
                entityExt.setFieldType(CustomerManagementEnum.LAST_CONNECT_TIME.getFieldType());
                entityExt.setSymbol((String) cusTimeRangeMap.get("symbol"));
                entityExt.setValue(value);
                // 归档
                ConditionsEntityExt cusArachivedEntityExt = aiAssistantConditionHelp.getArachivedCondition(CustomerManagementEnum.IS_ARCHIVED.getAttr(),
                        CustomerManagementEnum.IS_ARCHIVED.getFieldType());
                // 非公海客户
                ConditionsEntityExt cusIsPublicEntityExt = aiAssistantConditionHelp.getNoPublicCustomerCondition();

                list.add(entityExt);
                list.add(cusArachivedEntityExt);
                list.add(cusIsPublicEntityExt);
                break;
            // 遗忘机会
            case FORGET_OPPORTUNITY:
                Map<String, Object> oppTimeRangMap = getValidForgetDateRange(thenTime, now, value, symbol);
                List<Long> oppTimeRange = (List<Long>) oppTimeRangMap.get("value");
                value.clear();
                value.addAll(oppTimeRange);
                entityExt.setAttr(SalesOpportunityEnum.LAST_CONNECT_TIME.getAttr());
                entityExt.setFieldType(SalesOpportunityEnum.LAST_CONNECT_TIME.getFieldType());
                entityExt.setSymbol((String) oppTimeRangMap.get("symbol"));
                entityExt.setValue(value);
                // 归档条件
                ConditionsEntityExt oppArachivedEntityExt = aiAssistantConditionHelp.getArachivedCondition(SalesOpportunityEnum.IS_ARCHIVED.getAttr(),
                        SalesOpportunityEnum.IS_ARCHIVED.getFieldType());
                list.add(entityExt);
                list.add(oppArachivedEntityExt);
                break;
            // 遗忘供应商
            case FORGET_SUPPLIER:
                Map<String, Object> supTimeRangeMap = getValidForgetDateRange(thenTime, now, value, symbol);
                List<Long> supTimeRange = (List<Long>) supTimeRangeMap.get("value");
                value.clear();
                value.addAll(supTimeRange);
                entityExt.setAttr(SupplierEnum.LAST_CONNECT_TIME.getAttr());
                entityExt.setFieldType(SupplierEnum.LAST_CONNECT_TIME.getFieldType());
                entityExt.setSymbol((String) supTimeRangeMap.get("symbol"));
                entityExt.setValue(value);
                list.add(entityExt);
                break;
            // 未跟进客户
            case NO_CONNECT_CUSTOMER:
                value.clear();
                value.add(0);
                entityExt.setAttr(CustomerManagementEnum.LAST_CONNECT_TIME.getAttr());
                entityExt.setFieldType(CustomerManagementEnum.LAST_CONNECT_TIME.getFieldType());
                entityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                entityExt.setValue(value);
                // 归档
                ConditionsEntityExt cusArachivedEntityExt1 = aiAssistantConditionHelp.getArachivedCondition(CustomerManagementEnum.IS_ARCHIVED.getAttr(),
                        CustomerManagementEnum.IS_ARCHIVED.getFieldType());
                // 非公海客户
                ConditionsEntityExt cusIsPublicEntityExt1 = aiAssistantConditionHelp.getNoPublicCustomerCondition();

                list.add(entityExt);
                list.add(cusArachivedEntityExt1);
                list.add(cusIsPublicEntityExt1);
                break;
            // 未跟进供应商
            case NO_CONNECT_SUPPLIER:
                value.clear();
                value.add(0);
                entityExt.setAttr(SupplierEnum.LAST_CONNECT_TIME.getAttr());
                entityExt.setFieldType(SupplierEnum.LAST_CONNECT_TIME.getFieldType());
                entityExt.setSymbol(ConditionEnum.EMPTY.getSymbol());
                entityExt.setValue(value);
                list.add(entityExt);
                break;
            // 合同即将到期
            case CONTRACT_DEAD_LINE:
                list.add(getValidEstimateTimeRange(ContractEnum.DEADLINE.getAttr(), ContractEnum.DEADLINE.getFieldType(), symbol, value, thenTime, now));
                break;
            // 销售阶段
            case OPPORTUNITY_STAGE:
                entityExt.setAttr(SalesOpportunityEnum.SALE_STAGE.getAttr());
                entityExt.setFieldType(SalesOpportunityEnum.SALE_STAGE.getFieldType());
                entityExt.setSymbol(symbol);
                entityExt.setValue(value);
                list.add(entityExt);
                break;
            // 采购即将到货
            case PURCHASE_ARRIVE_TIME:
                list.add(getValidEstimateTimeRange(PurchaseEnum.ESTIMATE_ARRIVE_TIME.getAttr(), PurchaseEnum.ESTIMATE_ARRIVE_TIME.getFieldType(), symbol, value, thenTime, now));
                break;
            // 生产完成
            case PRODUCTION_ORDER_PLAN_TIME:
                list.add(getValidEstimateTimeRange(ProductionOrderEnum.PLAN_TIME.getAttr(), ProductionOrderEnum.PLAN_TIME.getFieldType(), symbol, value, thenTime, now));
                break;
            // 待采购
            case WAIT_PURCHASE:
                if (waitPurchaseDataIdSet.size() > 0) {
                    entityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
                    entityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                    entityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    entityExt.setValue(new ArrayList<>(waitPurchaseDataIdSet));
                    // 归档条件
                    ConditionsEntityExt arachivedEntityExt = aiAssistantConditionHelp.getArachivedCondition(ContractEnum.ARCHIVED.getAttr(),
                            ContractEnum.ARCHIVED.getFieldType());
                    // 未处理日期
                    ConditionsEntityExt untreatedEntityExt = getValidUntreatedDateRange(symbol, thenTime, now, value);

                    list.add(entityExt);
                    list.add(arachivedEntityExt);
                    list.add(untreatedEntityExt);
                }
                break;
            // 待生产
            case WAIT_PRODUCTION_ORDER:
                if (waitProduceDataIdSet.size() > 0) {
                    entityExt.setAttr(FieldTypeEnum.DATAID.getAlias());
                    entityExt.setFieldType(FieldTypeEnum.DATAID.getType());
                    entityExt.setSymbol(ConditionEnum.IN.getSymbol());
                    entityExt.setValue(new ArrayList<>(waitProduceDataIdSet));
                    // 归档条件
                    ConditionsEntityExt arachivedEntityExt = aiAssistantConditionHelp.getArachivedCondition(ContractEnum.ARCHIVED.getAttr(),
                            ContractEnum.ARCHIVED.getFieldType());

                    // 未处理日期
                    ConditionsEntityExt untreatedEntityExt = getValidUntreatedDateRange(symbol, thenTime, now, value);

                    list.add(entityExt);
                    list.add(arachivedEntityExt);
                    list.add(untreatedEntityExt);
                }
                break;
            // 待入库
            case WAIT_INSTOCK:
                value.clear();
                value.add(0);
                entityExt.setAttr(PurchaseEnum.ALL_INCOMING.getAttr());
                entityExt.setFieldType(PurchaseEnum.ALL_INCOMING.getFieldType());
                entityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                entityExt.setValue(value);

                // 未处理日期
                ConditionsEntityExt instockUntreatedEntityExt = getValidUntreatedDateRange(symbol, thenTime, now, value);

                list.add(entityExt);
                list.add(instockUntreatedEntityExt);
                break;
            // 待出库
            case WAIT_OUTSTOCK:
                value.clear();
                value.add(0);
                entityExt.setAttr(ContractEnum.ALL_OUT_BOUND.getAttr());
                entityExt.setFieldType(ContractEnum.ALL_OUT_BOUND.getFieldType());
                entityExt.setSymbol(ConditionEnum.EQUAL.getSymbol());
                entityExt.setValue(value);
                // 归档条件
                ConditionsEntityExt waitArachivedEntityExt = aiAssistantConditionHelp.getArachivedCondition(ContractEnum.ARCHIVED.getAttr(),
                        ContractEnum.ARCHIVED.getFieldType());

                // 未处理日期
                ConditionsEntityExt outstockUntreatedEntityExt = getValidUntreatedDateRange(symbol, thenTime, now, value);

                list.add(entityExt);
                list.add(waitArachivedEntityExt);
                list.add(outstockUntreatedEntityExt);
                break;
            // 产品库存下限预警
            case PRODUCT_STOCK_LOWER_WARNING:
                stockWarningConditionList.add(new ConditionsEntityExt(FieldTypeEnum.WAREHOUSE_CHECKED.getAlias(), "", FieldTypeEnum.WAREHOUSE_CHECKED.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1)));
                FieldTypeEnum lowerWarnTypeEnum = WarningSearchEnum.getWarnTypeEnum(2);
                stockWarningConditionList.add(new ConditionsEntityExt(lowerWarnTypeEnum.getAlias(), "", lowerWarnTypeEnum.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1)));
                break;
            // 产品库存上限预警
            case PRODUCT_STOCK_UPPER_WARNING:
                stockWarningConditionList.add(new ConditionsEntityExt(FieldTypeEnum.WAREHOUSE_CHECKED.getAlias(), "", FieldTypeEnum.WAREHOUSE_CHECKED.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1)));
                FieldTypeEnum upperWarnTypeEnum = WarningSearchEnum.getWarnTypeEnum(1);
                stockWarningConditionList.add(new ConditionsEntityExt(upperWarnTypeEnum.getAlias(), "", upperWarnTypeEnum.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1)));
                break;
            // 产品临期
            case PRODUCT_EXPIRE_WARNING:
                expireWarningConditionList.add(new ConditionsEntityExt(FieldTypeEnum.BATCH_WAREHOUSE_CHECKED.getAlias(), "", FieldTypeEnum.BATCH_WAREHOUSE_CHECKED.getType(), ConditionEnum.EQUAL.getSymbol(), Collections.singletonList(1)));
                // 保质期天数
                entityExt = getValidExpireTimeRange(FieldTypeEnum.BATCH_PRODUCE_DATE.getAlias(),FieldTypeEnum.BATCH_PRODUCE_DATE.getType(), symbol, value, thenTime, now);
                expireWarningConditionList.add(entityExt);
                break;
            // 回款到期、回款逾期
            case PAYMENT_DEAD_LINE:
            case PAYMENT_OVERDUE:
                list.add(getValidEstimateTimeRange(PaymentEnum.ESTIMATE_TIME.getAttr(), PaymentEnum.ESTIMATE_TIME.getFieldType(), symbol, value, thenTime, now));
                // 回款状态
                list.add(aiAssistantConditionHelp.getPaymentOrPayPlanStatusCondition(true));
                break;
            // 付款到期、回款逾期
            case PAY_PLAN_DEAD_LINE:
            case PAY_PLAN_OVERDUE:
                list.add(getValidEstimateTimeRange(PayPlanEnum.ESTIMATE_TIME.getAttr(), PayPlanEnum.ESTIMATE_TIME.getFieldType(), symbol, value, thenTime, now));
                // 付款状态
                list.add(aiAssistantConditionHelp.getPaymentOrPayPlanStatusCondition(false));
                break;
            default:
                break;
        }

        return list;
    }

    /**
     * 业务数据列表转换成表单实体列表
     *
     * @param list 业务数据列表
     * @return
     * @throws
     * @author hongxiao
     * @date: 2020-02-24 16:29
     * @since v4.13.0
     * @version v4.13.0
     */
    private List<PaasFormDataEntityExt> getFormDataList (List list) {
        List<PaasFormDataEntityExt> formDataList = new ArrayList<>();
        try {
            BeanUtil.copyPropertiesList(list, formDataList, PaasFormDataEntityExt.class);
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (XbbException e) {
            e.printStackTrace();
        }
        return formDataList;
    }


}
